name: Build and Publish to PyPI

on:
  workflow_dispatch:
    inputs: {}
  release:
    types: [published]

permissions:
  contents: write  # Needed to upload artifacts to the release
  id-token: write  # Needed for OIDC PyPI publishing

jobs:
  build:
    name: Build artifacts
    runs-on: ubuntu-latest
    environment: publishing

    steps:
    - name: Check out the repository
      uses: actions/checkout@v4.1.4

    - name: Install Poetry
      env:
        PIP_CONSTRAINT: ${{ github.workspace }}/.github/workflows/resources/constraints.txt
      run: |
        pipx install poetry
        poetry --version

    - name: Set up Python
      uses: actions/setup-python@v5.1.0
      with:
        python-version: 3.9
        architecture: x64
        cache: 'poetry'

    - name: Check version
      if: ${{ github.event.release }}
      run: |
        version=$(poetry version | awk '{print $2}')
        tag=$(echo "${{ github.ref }}" | awk '{split($0,p,"/"); print p[3]}')
        if [ "v$version" != $tag ]; then echo "Release tag ('$tag') and poetry version ('v$version') do not match!"; exit 1; fi;

    - name: Poetry install
      # Required to run `alembic_freeze.py`
      run: |
        poetry install

    - name: Freeze DB
      run: |
        poetry run scripts/alembic_freeze.py

    - name: Release Marker
      if: ${{ github.event.release }}
      # The release marker differentiates installations 'in the wild' versus internal dev builds and tests
      run: touch src/meltano/core/tracking/.release_marker

    - name: Build distribution
      run: |
        poetry build --format sdist
        poetry run pip wheel --no-deps . --wheel-dir dist/

    - name: Upload artifacts
      uses: actions/upload-artifact@v4
      with:
        name: python-artifacts
        path: 'dist/*'

  pypi_release:
    name: Publish to PyPI
    needs: [build]
    runs-on: ubuntu-latest
    environment: publishing
    steps:
    - name: Check out the repository
      uses: actions/checkout@v4.1.4

    - name: Download artifacts
      uses: actions/download-artifact@v4
      with:
        name: python-artifacts
        path: dist/

    - name: Verify artifacts
      run: |
        ls dist/

    - name: Upload wheel to release
      if: ${{ github.event.release }}
      uses: svenstaro/upload-release-action@v2
      with:
        repo_token: ${{ secrets.GITHUB_TOKEN }}
        file: dist/*.whl
        tag: ${{ github.ref }}
        overwrite: true
        file_glob: true

    - name: Publish
      if: ${{ github.event.release }}
      uses: pypa/gh-action-pypi-publish@v1.8.14
